const { Controller } = require('egg');
const jwt = require('jsonwebtoken')
const key = 'aaa'

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { userName,passWord } = ctx.request.body
    const data = await ctx.app.mysql.get('user',{
        userName
    })
    if(data){
        if(data.passWord==passWord){
            const token = jwt.sign({
                userName,
                id:data.id
            },key,{
                encoding:'2h'
            })
            ctx.body = {
                code:1,
                token,
                message:'登录成功'
            };
        }
        else{
            ctx.body = {
                code:0,
                message:'账号密码不匹配'
            };
        }
    }
    else{
        ctx.body = {
            code:0,
            message:'请先注册'
        };
    }
  }

  async register() {
    const { ctx } = this;
    const { userName,passWord } = ctx.request.body
    const data = await ctx.app.mysql.get('user',{
        userName
    })
    if(!data){
        if(data.passWord==passWord){
            await ctx.app.mysql.insert('user',{
                userName,
                passWord
            })
            ctx.body = {
                code:1,
                message:'注册成功'
            };
        }
    }
    else{
        ctx.body = {
            code:0,
            message:'该账号已注册'
        };
    }
  }
}

module.exports = UserController;
